package com.app.micaihu.view.main.fragment

import android.content.Context
import android.graphics.RectF
import android.os.Bundle
import android.util.TypedValue
import android.view.ViewTreeObserver
import androidx.fragment.app.Fragment
import com.app.base.BaseFragment
import com.app.hubert.guide.NewbieGuide
import com.app.hubert.guide.core.Controller
import com.app.hubert.guide.listener.OnGuideChangedListener
import com.app.hubert.guide.model.GuidePage
import com.app.hubert.guide.model.HighLight
import com.app.micaihu.R
import com.app.micaihu.configure.Config
import com.app.micaihu.configure.ConfigKeyConstant
import com.app.micaihu.configure.UmEventId
import com.app.micaihu.utils.MobclickAgentUtils
import com.app.micaihu.utils.StatServiceUtils
import com.app.micaihu.view.army.fragment.ArmyFollowListFragment
import com.app.micaihu.view.army.fragment.ArmyListFragment
import com.app.micaihu.view.main.adapter.TabLayoutViewPageAdapter
import com.app.micaihu.view.main.topic.fragment.TopicRecommendFragment
import com.app.micaihu.view.main.view.ScaleTransitionPagerTitleView
import com.blankj.utilcode.util.*
import com.jeremyliao.liveeventbus.LiveEventBus
import kotlinx.android.synthetic.main.main_legion_fragment.*
import net.lucode.hackware.magicindicator.ViewPagerHelper
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.SimplePagerTitleView

/**
 * 军团
 */
class LegionFragment : BaseFragment() {
    override fun getLayoutId() = R.layout.main_legion_fragment

    private var fragments: MutableList<Fragment> = arrayListOf()
    private var titles = listOf("话题", "军团", "关注")
    var left = 0
    var top = 0
    override fun setData() {
        hideLoading()
        BarUtils.addMarginTopEqualStatusBarHeight(magicIndicator)
    }

    override fun addListeners() {
        LiveEventBus.get(Config.EventBus.goArmy, Boolean::class.java).observe(this, { goArmy ->
            if (goArmy != null && goArmy) {
                viewPager.currentItem = 1
            }
        })
    }

    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        LogUtils.e(classTag, "isVisibleToUser->$isVisibleToUser")
        if (isVisibleToUser) {
            val showArmyGuide = SPUtils.getInstance().getBoolean(ConfigKeyConstant.showArmyGuide, false)
            if (!showArmyGuide) {
                showGuide()
            }
        }
    }

    private fun initFragment() {
        fragments.clear()
        val topicRecommendFragment = TopicRecommendFragment() //推荐话题
        val bundle = Bundle()
        bundle.putString("indexType", "1")
        topicRecommendFragment.arguments = bundle
        fragments.add(topicRecommendFragment)

        fragments.add(ArmyListFragment())

        fragments.add(ArmyFollowListFragment())

        val viewPageAdapter = TabLayoutViewPageAdapter(childFragmentManager, fragments, titles)
        viewPager.adapter = viewPageAdapter
        val commonNavigator = CommonNavigator(context)
        commonNavigator.adapter = object : CommonNavigatorAdapter() {
            override fun getCount(): Int {
                return fragments.size
            }

            override fun getTitleView(context: Context, index: Int): IPagerTitleView {
                val simplePagerTitleView: SimplePagerTitleView = ScaleTransitionPagerTitleView(context)
                simplePagerTitleView.text = titles[index]
                simplePagerTitleView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18f)
                simplePagerTitleView.normalColor = ColorUtils.getColor(R.color.white_70)
                simplePagerTitleView.selectedColor = ColorUtils.getColor(R.color.white)
                simplePagerTitleView.setOnClickListener {
                    when (index) {
                        0 -> {
                            StatServiceUtils.event(Config.EventBauduId.topictop_topic, "社区_广场")
                            MobclickAgentUtils.event(UmEventId.topictop_click, "话题")
                        }
                        1 -> {
                            StatServiceUtils.event(Config.EventBauduId.topictop_team, "社区_军团")
                            MobclickAgentUtils.event(UmEventId.topictop_click, "军团")
                        }
                        2 -> {
                            StatServiceUtils.event(Config.EventBauduId.topictop_attention, "社区_关注")
                            MobclickAgentUtils.event(UmEventId.topictop_click, "关注")
                        }
                    }
                    viewPager.currentItem = index
                }
                return simplePagerTitleView
            }

            override fun getIndicator(context: Context): IPagerIndicator {
                val indicator = LinePagerIndicator(context)
                indicator.lineHeight = 0f
                return indicator
            }

        }
        viewPager.offscreenPageLimit = fragments.size
        magicIndicator.navigator = commonNavigator
        ViewPagerHelper.bind(magicIndicator, viewPager)
    }

    override fun lazyLoad() {
        initFragment()
    }


    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        val viewTreeObserver: ViewTreeObserver = magicIndicator.viewTreeObserver
        viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                magicIndicator.viewTreeObserver.removeOnGlobalLayoutListener(this)
                left = magicIndicator.left
                top = magicIndicator.top
            }
        })
    }


    private fun showGuide() {
        NewbieGuide.with(this)
                .setLabel("guide1")
                .alwaysShow(true) //总是显示，调试时可以打开
                .setOnGuideChangedListener(object : OnGuideChangedListener {
                    override fun onShowed(controller: Controller) {}
                    override fun onRemoved(controller: Controller) {
                        SPUtils.getInstance().put(ConfigKeyConstant.showArmyGuide, true)
                    }
                })
                .addGuidePage(GuidePage.newInstance()
                        .setEverywhereCancelable(true) //是否点击任意位置消失引导页
                        .addHighLight(RectF(left.toFloat(), (top + SizeUtils.dp2px(5f)).toFloat(),
                                left + SizeUtils.dp2px(55f).toFloat(),
                                top + SizeUtils.dp2px(40f).toFloat()), HighLight.Shape.OVAL)
                        .setLayoutRes(R.layout.army_guide)
                        .setOnLayoutInflatedListener { view, controller ->

                        }
                ).show()
    }

}